{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "28b9c35e-ebf2-4198-a743-4ef229abc06f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0., 0., 0.],\n",
       "       [0., 0., 0.],\n",
       "       [0., 0., 0.]])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "np.zeros((3,3))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "95b905bd-03cc-4fc8-83b8-229fb88d9fc5",
   "metadata": {},
   "outputs": [],
   "source": [
    "zero_matrix_int = np.zeros((3, 3), dtype=int)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "aba41003-d99a-4db7-bb3f-cbee6611c93e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 0, 0],\n",
       "       [0, 0, 0],\n",
       "       [0, 0, 0]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "zero_matrix_int"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2c711dfa-57d0-42fe-a518-c1721b9b1ed8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('int64')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "zero_matrix_int.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "612e2b2d-68de-4cc5-b9ec-ee16cd48f417",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4 5]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 定义一个 Python 列表\n",
    "data = [1, 2, 3, 4, 5]\n",
    "\n",
    "# 使用 np.asarray() 转换为 NumPy 数组\n",
    "arr = np.asarray(data)\n",
    "\n",
    "print(arr)\n",
    "print(type(arr))  # 输出类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "88f450c5-c69c-4bd6-b574-7738b1952680",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 4]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "import numpy as np\n",
    "\n",
    "# 定义一个 bytes 对象\n",
    "data = b'\\x01\\x02\\x03\\x04'  # 4 个字节（0x01, 0x02, 0x03, 0x04）\n",
    "\n",
    "# 转换为 uint8（无符号 8 位整数）数组\n",
    "arr = np.frombuffer(data, dtype=np.uint8)\n",
    "\n",
    "print(arr)  # 输出：[1 2 3 4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "1d30e89b-0fbb-44d5-8ce2-0a8161f9d3e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 6 7 8]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# 使用 memoryview 包装 bytes\n",
    "buffer = memoryview(b'\\x05\\x06\\x07\\x08')\n",
    "arr = np.frombuffer(buffer, dtype=np.uint8)\n",
    "\n",
    "print(arr)  # 输出：[5 6 7 8]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ad8c074-887f-4804-83d5-9d6d479820f9",
   "metadata": {},
   "source": [
    "## 高效处理可迭代数据\t比 np.array() 更节省内存"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "08cdbb0c-ea6c-46d8-b485-42ebea89a10c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[10 20 30 40 50]\n",
      "[0 2 4 6 8]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "# 定义一个列表\n",
    "data = [10, 20, 30, 40, 50]\n",
    "\n",
    "# 转换为 NumPy 数组\n",
    "arr = np.fromiter(data, dtype=np.int32)\n",
    "\n",
    "print(arr)  # 输出：[10 20 30 40 50]\n",
    "\n",
    "\n",
    "# 定义一个生成器\n",
    "def gen_numbers():\n",
    "    for i in range(5):\n",
    "        yield i * 2  # 生成 0, 2, 4, 6, 8\n",
    "\n",
    "# 转换为 NumPy 数组\n",
    "arr = np.fromiter(gen_numbers(), dtype=np.int32)\n",
    "\n",
    "print(arr)  # 输出：[0 2 4 6 8]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "725bb5a8-4335-47ca-a5c9-e0edccac5810",
   "metadata": {},
   "source": [
    "## np.loadtxt() 适合 小型结构化数据，如果数据较复杂（如混合类型、缺失值），建议使用 pandas.read_csv() 或 np.genfromtxt()。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "144a2bf3-2baa-40ff-ba96-8c450ae62a86",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"  txt\n",
    "1 2 3\n",
    "4 5 6\n",
    "7 8 9\n",
    "\"\"\"\n",
    "\n",
    "\"\"\"  csv\n",
    "10,20,30\n",
    "40,50,60\n",
    "70,80,90\n",
    "\"\"\"\n",
    "data = np.loadtxt(\"data.txt\")\n",
    "data = np.loadtxt(\"data.csv\", delimiter=\",\")\n",
    "data = np.loadtxt(\"data.csv\", delimiter=\",\", skiprows=1)\n",
    "data = np.loadtxt(\"data.txt\", dtype=np.int32)  # 强制转为整数\n",
    "data = np.loadtxt(\"data.csv\", delimiter=\",\", skiprows=1, usecols=(0, 2))  # 只加载第 1 列和第 3 列（索引 0 和 2）\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17972833-0759-4f35-a97d-61e3349e59f6",
   "metadata": {},
   "source": [
    "### np.genfromtxt() 是 NumPy 中一个强大的函数，用于从文本文件加载数据并处理更复杂的情况，如缺失值、混合数据类型等。相比 np.loadtxt()，它提供了更多灵活的功能"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8aed356-7273-44ae-8008-d3d023333118",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "data = np.genfromtxt(\"data_with_nan.csv\", delimiter=\",\", filling_values=0)\n",
    "\n",
    "\"\"\"\n",
    "1,2,NA\n",
    "4,5,6\n",
    "7,8,9\n",
    "\"\"\"\n",
    "def conv(val):\n",
    "    if val == b'NA':\n",
    "        return np.nan\n",
    "    return float(val)\n",
    "\n",
    "data = np.genfromtxt('special.csv', delimiter=',', converters={2: conv})   #    转换器处理特殊值\n",
    "print(data)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e1b1f8cf-c7e8-4ca7-9e9a-5de50bee6976",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "原数组:\n",
      " [0 1 2 3 4 5]\n",
      "重塑后:\n",
      " [[0 1 2]\n",
      " [3 4 5]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "arr = np.arange(6)  # [0, 1, 2, 3, 4, 5]\n",
    "reshaped = arr.reshape(2, 3)\n",
    "\n",
    "print(\"原数组:\\n\", arr)\n",
    "print(\"重塑后:\\n\", reshaped)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c1feb517-bb92-482a-8c67-56ae68b8df28",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, 8)\n",
      "(2, 3, 4)\n"
     ]
    }
   ],
   "source": [
    "arr = np.arange(24)\n",
    "\n",
    "# 自动计算第二个维度大小\n",
    "reshaped = arr.reshape(3, -1)  # 等价于reshape(3,8)\n",
    "print(reshaped.shape)  # 输出 (3, 8)\n",
    "\n",
    "# 自动计算其他维度\n",
    "reshaped = arr.reshape(2, 3, -1)\n",
    "print(reshaped.shape)  # 输出 (2, 3, 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "175dc35e-31ff-4b19-b17b-a6acd8b1d860",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4, 5, 6)\n",
      "(4, 30)\n"
     ]
    }
   ],
   "source": [
    "arr = np.random.rand(4, 5, 6)\n",
    "print(arr.shape)\n",
    "reshaped = arr.reshape(4, -1)  # 保持4行，展平后面的维度\n",
    "print(reshaped.shape)  # 输出 (4, 30)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "fbcde440-8121-4220-a366-964b6a06767e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2]\n",
      " [3 4 5]]\n",
      "C顺序(行优先):\n",
      " [[0 1 2]\n",
      " [3 4 5]]\n",
      "F顺序(列优先):\n",
      " [[0 2 4]\n",
      " [1 3 5]]\n",
      "A顺序(列优先):\n",
      " [[0 1 2]\n",
      " [3 4 5]]\n"
     ]
    }
   ],
   "source": [
    "arr = np.arange(6)\n",
    "n_arr = arr.reshape(2,-1)\n",
    "print(n_arr)\n",
    "\n",
    "print(\"C顺序(行优先):\\n\", arr.reshape(2, 3, order='C'))\n",
    "print(\"F顺序(列优先):\\n\", arr.reshape(2, 3, order='F'))\n",
    "print(\"\\n\", arr.reshape(2, 3, order='A'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "28328c03-6a86-4856-9689-6f8bbf643a19",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]] -----------\n",
      "[[1 2 3]\n",
      " [4 1 2]\n",
      " [3 4 1]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "arr = np.array([[1, 2], [3, 4]])\n",
    "print(arr, \"-----------\")\n",
    "\n",
    "resized = np.resize(arr, (3, 3))  # 自动重复元素填充\n",
    "print(resized)\n",
    "# 输出：\n",
    "# [[1 2 3]\n",
    "#  [4 1 2]\n",
    "#  [3 4 1]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9eded263-ecdf-4532-ab92-1f449a5668a6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "ff230b4e-f939-47d5-8ff7-0ab5da1610d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]] ----arr\n",
      "[1 2 3 4]\n",
      "[[100   2]\n",
      " [  3   4]]\n",
      "[100   2   3   4] -----\n"
     ]
    }
   ],
   "source": [
    "arr = np.array([[1, 2], [3, 4]])\n",
    "print(arr, \"----arr\")\n",
    "flattened = arr.ravel()  # 不复制数据\n",
    "print(flattened)  # [1 2 3 4]\n",
    "flattened[0] = 100  # 会修改原数组\n",
    "print(arr)  # [[100   2] [  3   4]]\n",
    "print(flattened, \"-----\") "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "7bbe69dc-23e2-4cfe-9883-f34077da6b4d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]]\n",
      "[100   2   3   4] -----\n"
     ]
    }
   ],
   "source": [
    "arr = np.array([[1, 2], [3, 4]])\n",
    "flattened = arr.flatten()  # 创建副本\n",
    "flattened[0] = 100  # 不会修改原数组\n",
    "print(arr)  # [[1 2] [3 4]]\n",
    "print(flattened, \"-----\") "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "db52006b-92f2-4f3d-ab69-60fccf19fa59",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "1de429b3-35e2-4344-a52b-e3cb1ed5b069",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2]\n",
      " [3 4 5]] ----arr\n",
      "[[0 3]\n",
      " [1 4]\n",
      " [2 5]]\n"
     ]
    }
   ],
   "source": [
    "arr = np.arange(6).reshape(2, 3)\n",
    "print(arr, \"----arr\")\n",
    "print(arr.T)  # 等价于 arr.transpose()\n",
    "# 输出：\n",
    "# [[0 3]\n",
    "#  [1 4]\n",
    "#  [2 5]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39e48067-fcb5-43b4-821b-5b50a810a61c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "830c3be8-f5f2-4e74-96b6-e09967ba8b30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[0 1]\n",
      "  [2 3]]\n",
      "\n",
      " [[4 5]\n",
      "  [6 7]]]\n",
      "(2, 2, 2)\n",
      "[[[0 4]\n",
      "  [2 6]]\n",
      "\n",
      " [[1 5]\n",
      "  [3 7]]]\n"
     ]
    }
   ],
   "source": [
    "arr = np.arange(8).reshape(2, 2, 2)\n",
    "print(arr)\n",
    "swapped = np.swapaxes(arr, 0, 2)  # 交换第0和第2轴\n",
    "print(swapped.shape)  # (2, 2, 2) 但轴顺序改变\n",
    "print(swapped)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "4b5819da-ad21-4cab-8563-b5b22ef040b3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [1 2 3]\n",
      " [1 2 3]]\n",
      "[1 2 3 1 2 3 1 2 3]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "arr = np.array([1, 2, 3])\n",
    "broadcasted = np.broadcast_to(arr, (3, 3))  # 广播到3x3\n",
    "print(broadcasted)\n",
    "# 输出：\n",
    "# [[1 2 3]\n",
    "#  [1 2 3]\n",
    "#  [1 2 3]]\n",
    "print(broadcasted.flatten())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "8e9cd4e6-cfde-4c8a-8205-26df106a0e38",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 4]\n",
      " [5 6]]\n",
      "[[1 2 7]\n",
      " [3 4 8]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([[1, 2], [3, 4]])\n",
    "b = np.array([[5, 6]])\n",
    "\n",
    "# 沿轴0连接（垂直/行方向）\n",
    "print(np.concatenate((a, b), axis=0))\n",
    "# [[1 2]\n",
    "#  [3 4]\n",
    "#  [5 6]]\n",
    "\n",
    "# 沿轴1连接（水平/列方向）\n",
    "c = np.array([[7], [8]])\n",
    "print(np.concatenate((a, c), axis=1))\n",
    "# [[1 2 7]\n",
    "#  [3 4 8]]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "fb2da3e7-450e-4809-8f01-50262b4d0ae8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "[[1 4]\n",
      " [2 5]\n",
      " [3 6]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\"\"\"\n",
    "创建新轴：始终沿着新的轴堆叠数组，会增加数组的维度。\n",
    "输入要求：所有输入数组必须具有完全相同的形状。\n",
    "灵活性：通过 axis 参数可以控制新轴的位置（默认 axis=0）。\n",
    "\"\"\"\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = np.array([4, 5, 6])\n",
    "\n",
    "# 默认沿新轴0堆叠\n",
    "print(np.stack((a, b)))\n",
    "# [[1 2 3]\n",
    "#  [4 5 6]]\n",
    "\n",
    "# 沿新轴1堆叠\n",
    "print(np.stack((a, b), axis=1))\n",
    "# [[1 4]\n",
    "#  [2 5]\n",
    "#  [3 6]]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9432a81b-cc4f-45cc-9c5b-8fb9263addf4",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = np.array([4, 5, 6])\n",
    "\n",
    "print(np.vstack((a, b)))\n",
    "# [[1 2 3]\n",
    "#  [4 5 6]]\n",
    "\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = np.array([4, 5, 6])\n",
    "\n",
    "print(np.hstack((a, b)))  # [1 2 3 4 5 6]\n",
    "\n",
    "# 对2D数组\n",
    "c = np.array([[1], [2]])\n",
    "d = np.array([[3], [4]])\n",
    "print(np.hstack((c, d)))\n",
    "# [[1 3]\n",
    "#  [2 4]]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99fb1ebc-8b2d-46f7-a78b-053a9438d6cd",
   "metadata": {},
   "source": [
    "### 需要增加维度时 → 用 stack（如将多个样本从向量转为矩阵）。\n",
    "\n",
    "### 需要按行合并 → 用 vstack（合并样本或扩展行）。\n",
    "\n",
    "### 需要按列合并 → 用 hstack（合并特征或扩展列）。\n",
    "\n",
    "### 构建数据集：X = np.vstack([sample1, sample2, sample3])\n",
    "\n",
    "### 合并特征：X_features = np.hstack([feature1, feature2])\n",
    "\n",
    "### 创建批次数据：batch = np.stack([img1, img2, img3])（形状 (3, H, W)）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "697065e7-deeb-4232-a386-433fa1b528e2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "994f9c71-ce2c-4cfd-b4b6-d82352ebcd3e",
   "metadata": {},
   "source": [
    "# 函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "7d668bf6-045f-4537-91ee-578632f5d7e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 7 9]\n",
      "[-3 -3 -3]\n",
      "[ 4 10 18]\n",
      "[0.25 0.4  0.5 ]\n",
      "[0 0 0]\n",
      "[4 2 2]\n",
      "[1 4 9]\n",
      "[  1  32 729]\n",
      "[0 1 0]\n",
      "[1 2 0]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = np.array([4, 5, 6])\n",
    "\n",
    "# 加法\n",
    "print(np.add(a, b))        # [5 7 9]\n",
    "\n",
    "# 减法\n",
    "print(np.subtract(a, b))   # [-3 -3 -3]\n",
    "\n",
    "# 乘法（逐元素相乘）\n",
    "print(np.multiply(a, b))   # [ 4 10 18]\n",
    "\n",
    "# 除法\n",
    "print(np.divide(a, b))     # [0.25 0.4  0.5 ]\n",
    "\n",
    "# 地板除法（向下取整）\n",
    "print(np.floor_divide(a, b))  # [0 0 0]\n",
    "print(np.floor_divide(b, a))  # [4 2 2]\n",
    "\n",
    "# 幂运算\n",
    "print(np.power(a, 2))      # [1 4 9]\n",
    "print(np.power(a, b))      # [  1  32 729]\n",
    "\n",
    "# 取模运算\n",
    "print(np.mod(b, a))        # [0 1 0]\n",
    "print(np.mod(a, 3))        # [1 2 0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "7b3522ca-378c-4c38-8365-7b153217e743",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 2.   1.  -0.  -1.5 -2.3]\n",
      "[-2.  -1.   0.   1.5  2.3]\n",
      "[2.  1.  0.  1.5 2.3]\n",
      "[2.  1.  0.  1.5 2.3]\n",
      "[-2. -1.  0.  2.  2.]\n",
      "[-1. -1.  0.  1.  1.]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\n",
    "\n",
    "arr = np.array([-2, -1, 0, 1.5, 2.3])\n",
    "\n",
    "# 负号运算\n",
    "print(np.negative(arr))    # [ 2.   1.  -0.  -1.5 -2.3]\n",
    "\n",
    "# 正号运算（实际不改变值）\n",
    "print(np.positive(arr))    # [-2.  -1.   0.   1.5  2.3]\n",
    "\n",
    "# 绝对值\n",
    "print(np.abs(arr))         # [2.  1.  0.  1.5 2.3]\n",
    "\n",
    "# 浮点绝对值（对整数也返回浮点）\n",
    "print(np.fabs(arr))        # [2.  1.  0.  1.5 2.3]\n",
    "\n",
    "# 四舍五入到最近整数\n",
    "print(np.rint(arr))        # [-2. -1.  0.  2.  2.]\n",
    "\n",
    "# 符号函数\n",
    "print(np.sign(arr))        # [-1. -1.  0.  1.  1.]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "bd1cd58c-0e8d-4374-b07f-7cf1eb38c566",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[11 22]\n",
      " [13 24]]\n",
      "[[10 40]\n",
      " [30 80]]\n"
     ]
    }
   ],
   "source": [
    "x = np.array([[1, 2], [3, 4]])\n",
    "y = np.array([10, 20])\n",
    "\n",
    "# 广播加法\n",
    "print(np.add(x, y))  \n",
    "# [[11 22]\n",
    "#  [13 24]]\n",
    "\n",
    "# 广播乘法\n",
    "print(np.multiply(x, y))\n",
    "# [[10 40]\n",
    "#  [30 80]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "a8ce885f-dc75-4009-998c-99c98702bb52",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1. inf -1.  0. -0. nan]\n",
      "[ 1.  0.  1. nan nan nan]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_176531/3649694335.py:4: RuntimeWarning: divide by zero encountered in divide\n",
      "  print(np.divide(1, arr))\n",
      "/tmp/ipykernel_176531/3649694335.py:8: RuntimeWarning: invalid value encountered in remainder\n",
      "  print(np.mod(arr, 2))\n"
     ]
    }
   ],
   "source": [
    "arr = np.array([1, 0, -1, np.inf, -np.inf, np.nan])\n",
    "\n",
    "# 除法安全示例\n",
    "print(np.divide(1, arr))\n",
    "# [ 1.  inf -1.  0. -0.  nan]\n",
    "\n",
    "# 模运算处理0\n",
    "print(np.mod(arr, 2))\n",
    "# [1. 0. 1. nan nan nan]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ac579ad-4032-4cca-8f3c-4bc8b5a2e342",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "5ba062aa-cd72-4099-9f07-7c8cd271dd57",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[False  True  True False False]\n",
      "[False  True  True False False]\n",
      "[ True False False  True  True]\n",
      "[ True False False  True  True]\n",
      "[ True False False False False]\n",
      "[ True False False False False]\n",
      "[ True  True  True False False]\n",
      "[ True  True  True False False]\n",
      "[False False False  True  True]\n",
      "[False False False  True  True]\n",
      "[False  True  True  True  True]\n",
      "[False  True  True  True  True]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3, 4, 5])\n",
    "b = np.array([5, 2, 3, 1, 4])\n",
    "\n",
    "# 等于比较\n",
    "print(np.equal(a, b))       # [False  True  True False False]\n",
    "print(a == b)              # 等价操作\n",
    "\n",
    "# 不等于比较\n",
    "print(np.not_equal(a, b))   # [ True False False  True  True]\n",
    "print(a != b)              # 等价操作\n",
    "\n",
    "# 小于比较\n",
    "print(np.less(a, b))       # [ True False False False False]\n",
    "print(a < b)               # 等价操作\n",
    "\n",
    "# 小于等于比较\n",
    "print(np.less_equal(a, b))  # [ True  True  True False False]\n",
    "print(a <= b)              # 等价操作\n",
    "\n",
    "# 大于比较\n",
    "print(np.greater(a, b))     # [False False False  True  True]\n",
    "print(a > b)               # 等价操作\n",
    "\n",
    "# 大于等于比较\n",
    "print(np.greater_equal(a, b))  # [False  True  True  True  True]\n",
    "print(a >= b)                 # 等价操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a1b23218-c926-4366-8d86-765092edebfa",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "5009682f-c352-45cd-8c83-6138869897a0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 5 10 15] [ 3  7 12]\n",
      "[ 1  2 12]\n",
      "[ 7 15 15]\n",
      "[ 6 13  3]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 创建两个整数数组\n",
    "a = np.array([5, 10, 15], dtype=np.uint8)  # 二进制: 0101, 1010, 1111\n",
    "b = np.array([3, 7, 12], dtype=np.uint8)   # 二进制: 0011, 0111, 1100\n",
    "\n",
    "print(a, b)\n",
    "\n",
    "# 按位与 (AND)\n",
    "print(np.bitwise_and(a, b))  # [1 2 12]\n",
    "# 解释：\n",
    "# 5 & 3 = 0101 & 0011 = 0001 (1)\n",
    "# 10 & 7 = 1010 & 0111 = 0010 (2)\n",
    "# 15 & 12 = 1111 & 1100 = 1100 (12)\n",
    "\n",
    "# 按位或 (OR)\n",
    "print(np.bitwise_or(a, b))   # [7 15 15]\n",
    "# 5 | 3 = 0101 | 0011 = 0111 (7)\n",
    "# 10 | 7 = 1010 | 0111 = 1111 (15)\n",
    "# 15 | 12 = 1111 | 1100 = 1111 (15)\n",
    "\n",
    "# 按位异或 (XOR)\n",
    "print(np.bitwise_xor(a, b))  # [6 13 3]\n",
    "# 5 ^ 3 = 0101 ^ 0011 = 0110 (6)\n",
    "# 10 ^ 7 = 1010 ^ 0111 = 1101 (13)\n",
    "# 15 ^ 12 = 1111 ^ 1100 = 0011 (3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "43952f4f-4a27-4fc7-a548-0702734231c8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[250 245 240]\n",
      "[250 245 240]\n",
      "[0 1]\n"
     ]
    }
   ],
   "source": [
    "# 按位取反 (NOT)\n",
    "print(np.bitwise_not(a))     # [250 245 240]\n",
    "print(np.invert(a))          # 与bitwise_not完全等价\n",
    "# 解释（8位无符号整数）：\n",
    "# ~0101 = 11111010 (250)\n",
    "# ~1010 = 11110101 (245)\n",
    "# ~1111 = 11110000 (240)\n",
    "\n",
    "# 有符号整数的情况\n",
    "c = np.array([-1, -2], dtype=np.int8)\n",
    "print(np.bitwise_not(c))     # [0 1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "c833c776-7ed7-41f6-9089-25675e2bf3fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[20 40 60]\n",
      "[2 5 7]\n"
     ]
    }
   ],
   "source": [
    "# 左移运算\n",
    "print(np.left_shift(a, 2))   # [20 40 60]\n",
    "# 5 << 2 = 0101 → 010100 (20)\n",
    "# 10 << 2 = 1010 → 101000 (40)\n",
    "# 15 << 2 = 1111 → 111100 (60)\n",
    "\n",
    "# 右移运算\n",
    "print(np.right_shift(a, 1))  # [2 5 7]\n",
    "# 5 >> 1 = 0101 → 0010 (2)\n",
    "# 10 >> 1 = 1010 → 0101 (5)\n",
    "# 15 >> 1 = 1111 → 0111 (7)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "8b1746ef-a960-4d81-adff-b7d31f5a9659",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[False False  True]\n",
      "[ True False  True]\n",
      "[ True False False]\n"
     ]
    }
   ],
   "source": [
    "# 布尔数组的位运算（等价于逻辑运算）\n",
    "bool_a = np.array([True, False, True])\n",
    "bool_b = np.array([False, False, True])\n",
    "\n",
    "print(np.bitwise_and(bool_a, bool_b))  # [False False  True]\n",
    "print(np.bitwise_or(bool_a, bool_b))   # [ True False  True]\n",
    "print(np.bitwise_xor(bool_a, bool_b))  # [ True False False]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "1913d26a-1abb-48cd-b58c-342cde457b4c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ True False False]\n",
      "[[128 240]\n",
      " [  0  64]]\n"
     ]
    }
   ],
   "source": [
    "# 标志位操作示例\n",
    "FLAG_A = 0b0001\n",
    "FLAG_B = 0b0010\n",
    "FLAG_C = 0b0100\n",
    "\n",
    "flags = np.array([FLAG_A | FLAG_C, FLAG_B, 0], dtype=np.uint8)\n",
    "\n",
    "# 检查是否设置了FLAG_A\n",
    "has_flag_a = np.bitwise_and(flags, FLAG_A) != 0\n",
    "print(has_flag_a)  # [ True False False]\n",
    "\n",
    "# 图像掩码处理\n",
    "image = np.array([[128, 255], [0, 64]], dtype=np.uint8)\n",
    "mask = np.bitwise_and(image, 0b11110000)  # 取高4位\n",
    "print(mask)\n",
    "# [[128 240]\n",
    "#  [  0  64]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "457c19c6-4a71-4341-8ccf-950967c5f9a5",
   "metadata": {},
   "source": [
    "## bitwise_and\t按位与\t&\t整数/布尔\n",
    "## bitwise_or\t按位或\t|\t整数/布尔\n",
    "## bitwise_xor\t按位异或\t^\t整数/布尔\n",
    "## bitwise_not/invert\t按位取反\t~\t整数/布尔\n",
    "## left_shift\t左移\t<<\t整数\n",
    "## right_shift\t右移\t>>\t整数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4992ea2-b6e6-4dc3-8024-b169e1cc37e7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "83d6c635-92ce-4973-8323-d0c216fc4d4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 7 9]\n",
      "[  6 120]\n",
      "[5 7 9]\n",
      "[  6 120]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "arr = np.array([[1, 2, 3],  [4, 5, 6]])\n",
    "\n",
    "# 沿轴0求和（垂直方向）\n",
    "print(np.add.reduce(arr, axis=0))  # [5 7 9]\n",
    "\n",
    "# 沿轴1求乘积（水平方向）\n",
    "print(np.multiply.reduce(arr, axis=1))  # [6 120]\n",
    "\n",
    "# 等价操作\n",
    "print(arr.sum(axis=0))  # 与np.add.reduce相同\n",
    "print(arr.prod(axis=1)) # 与np.multiply.reduce相同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "7b4df859-86ac-441b-bd13-1f4f1c15e755",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1  3  6 10]\n",
      "[ 1  2  6 24]\n",
      "[[1 2]\n",
      " [4 6]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "a = np.array([1, 2, 3, 4])\n",
    "\n",
    "# 累积求和\n",
    "print(np.add.accumulate(a))  # [1 3 6 10]\n",
    "\n",
    "# 累积乘积\n",
    "print(np.multiply.accumulate(a))  # [1 2 6 24]\n",
    "\n",
    "# 二维数组示例\n",
    "b = np.array([[1, 2], [3, 4]])\n",
    "print(np.add.accumulate(b, axis=0))\n",
    "# [[1 2]\n",
    "#  [4 6]]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "02d1f2db-0f7c-43d5-8fb3-e2fb48302296",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 6  4 11]\n",
      "[[0 1 2]\n",
      " [3 4 5]\n",
      " [6 7 8]]\n",
      "[[1 2]\n",
      " [4 5]\n",
      " [7 8]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\n",
    "arr = np.array([1, 2, 3, 4, 5, 6])\n",
    "indices = [0, 3, 4]  # 切片位置：[0:3], [3:4], [4:6]\n",
    "\n",
    "# 分段求和\n",
    "print(np.add.reduceat(arr, indices))  # [6 4 11]\n",
    "\n",
    "# 矩阵分段示例\n",
    "mat = np.arange(9).reshape(3,3)\n",
    "print(mat)\n",
    "print(np.maximum.reduceat(mat, [0, 2], axis=1))\n",
    "#  【02】 从第0 到 2 前一列，   -------   从第2 列  到 最后\n",
    "#   maximum 求最大值\n",
    "# [[0 2]\n",
    "#  [3 5]\n",
    "#  [6 8]]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "ca863ace-4e08-4a7f-9656-b00c5800da4e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[5 6]\n",
      " [6 7]\n",
      " [7 8]]\n",
      "[[5 6 7]\n",
      " [6 7 8]]\n",
      "[[False False]\n",
      " [False False]\n",
      " [False False]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\n",
    "x = np.array([1, 2, 3])\n",
    "y = np.array([4, 5])\n",
    "\n",
    "# 外积求和\n",
    "print(np.add.outer(x, y))\n",
    "# [[5 6]\n",
    "#  [6 7]\n",
    "#  [7 8]]\n",
    "\n",
    "\n",
    "print(np.add.outer(y, x))\n",
    "\n",
    "\n",
    "\n",
    "# 外积比较\n",
    "print(np.greater.outer(x, y))\n",
    "# [[False False]\n",
    "#  [False False]\n",
    "#  [ True  True]]\n",
    "\n",
    "# # 实际应用：计算距离矩阵\n",
    "# points = np.array([0, 1, 3])\n",
    "# print(np.abs.outer(points, points))\n",
    "# # [[0 1 3]\n",
    "# #  [1 0 2]\n",
    "# #  [3 2 0]]\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "9aa008fe-360e-4848-8231-79e0ae75978c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 0 0 0 0]\n",
      "[1 2 0 1 0]\n",
      "[[0. 0. 0.]\n",
      " [0. 0. 0.]\n",
      " [0. 0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "\n",
    "arr = np.zeros(5, dtype=int)\n",
    "indices = [0, 1, 1, 3]\n",
    "print(arr)\n",
    "\n",
    "# 在指定索引处累加（避免重复索引的缓冲问题）\n",
    "np.add.at(arr, indices, 1)\n",
    "print(arr)  # [1 2 0 1 0]\n",
    "# indices = [0, 1, 1, 3]，所以：\n",
    "# arr[0] += 1 → arr = [1, 0, 0, 0, 0]\n",
    "# arr[1] += 1 → arr = [1, 1, 0, 0, 0]\n",
    "# arr[1] += 1 → arr = [1, 2, 0, 0, 0]\n",
    "# arr[3] += 1 → arr = [1, 2, 0, 1, 0]\n",
    "# 最终 arr = [1, 2, 0, 1, 0]。\n",
    "\n",
    "\n",
    "\n",
    "# 复杂示例\n",
    "mat = np.zeros((3,3))\n",
    "rows = [0, 1, 0]\n",
    "cols = [0, 1, 0]\n",
    "np.multiply.at(mat, (rows, cols), [2, 3, 4])  # 在 mat 的 (rows[i], cols[i]) 位置逐个乘以给定的值（不会合并重复索引）\n",
    "# 普通 mat[rows, cols] *= [2, 3, 4] 会对重复位置只乘一次，而 np.multiply.at 会正确处理重复索引\n",
    "print(mat)\n",
    "# [[0. 0. 0.]\n",
    "#  [0. 0. 0.]\n",
    "#  [0. 0. 0.]]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "690ce20e-290a-42eb-887d-162a70928e70",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30350d69-f0df-4bbf-9d6b-0264cb7883ae",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed80bcd1-f576-45f2-8230-eaed4aa8d828",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "55f2df4f-0577-4d4c-b11b-9ac1845f88e4",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fa54fc6-b6cb-4079-bae3-2e6090c38274",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88748e3d-6293-41af-b557-196ad9726ba5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36135913-3da3-4b4a-90ab-1916fed30cca",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ae62891-5aae-4e5b-83cd-9174340707db",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d70ff38-c323-4091-9883-363393fb94e9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccb9194c-f822-4b83-afd6-d25cef304528",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c5accbf-dfcc-4e34-bb25-e7ebbf3cea44",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c604595-a078-4d1d-b1fc-b89d6421d217",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20591ad5-a5b0-43a3-8837-adebda231cf8",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf8eb0a2-97f2-43d2-966d-0a58365d1c8b",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de44915b-ddcf-41f5-8d99-269e2504ce02",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2661ba05-caa1-4ed1-9d5d-2d1623513982",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
